﻿using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.NetworkAnalyst;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

namespace MapFormsApp.Models
{
    /// <summary>
    /// 路径规划结果模型（支持数据绑定和几何操作）
    /// </summary>
    public class PathResult : INotifyPropertyChanged
    {
        #region 属性定义
        private IPolyline _pathGeometry;
        private double _totalDistance;
        private double _totalTime;
        private List<PathSegment> _segments;
        private bool _isSuccess;
        private string _errorMessage;

        /// <summary>
        /// 路径几何形状（折线）
        /// </summary>
        public IPolyline PathGeometry
        {
            get => _pathGeometry;
            set => SetField(ref _pathGeometry, value);
        }

        /// <summary>
        /// 总路径长度（米）
        /// </summary>
        public double TotalDistance
        {
            get => _totalDistance;
            set => SetField(ref _totalDistance, value);
        }

        /// <summary>
        /// 预计通行时间（分钟）
        /// </summary>
        public double TotalTime
        {
            get => _totalTime;
            set => SetField(ref _totalTime, value);
        }

        /// <summary>
        /// 路径分段详细信息
        /// </summary>
        public List<PathSegment> Segments
        {
            get => _segments;
            set => SetField(ref _segments, value);
        }

        /// <summary>
        /// 路径是否计算成功
        /// </summary>
        public bool IsSuccess
        {
            get => _isSuccess;
            set => SetField(ref _isSuccess, value);
        }

        /// <summary>
        /// 错误信息（当IsSuccess为false时有效）
        /// </summary>
        public string ErrorMessage
        {
            get => _errorMessage;
            set => SetField(ref _errorMessage, value);
        }
        #endregion

        #region 构造方法
        /// <summary>
        /// 从网络分析结果创建路径对象
        /// </summary>
        public static PathResult FromRouteFeature(IFeature routeFeature, INetworkDataset networkDataset)
        {
            var result = new PathResult
            {
                PathGeometry = routeFeature.ShapeCopy as IPolyline,
                IsSuccess = true
            };

            // 计算总距离和时间
            result.TotalDistance = CalculateTotalLength(routeFeature);
            result.TotalTime = CalculateTotalTime(routeFeature, networkDataset);

            // 解析路径分段
            result.Segments = ParseSegments(routeFeature, networkDataset);

            return result;
        }
        #endregion

        #region 核心计算方法
        private static double CalculateTotalLength(IFeature routeFeature)
        {
            ICurve curve = routeFeature.Shape as ICurve;
            return curve?.Length ?? 0;
        }

        private static double CalculateTotalTime(IFeature routeFeature, INetworkDataset networkDataset)
        {
            double totalTime = 0;
            int timeAttrIndex = routeFeature.Fields.FindField("WalkTime");

            if (timeAttrIndex != -1)
            {
                IFeatureWorkspace featureWorkspace = (IFeatureWorkspace)networkDataset;
                ITable histTable = featureWorkspace.OpenTable("道路_ND_时间属性");
                // 这里需要根据实际网络数据集属性进行时间计算
                // 示例实现：
                foreach (PathSegment segment in ParseSegments(routeFeature, networkDataset))
                {
                    totalTime += segment.TimeCost;
                }
            }
            return totalTime / 60; // 转换为分钟
        }
        #endregion

        #region 路径解析
        private static List<PathSegment> ParseSegments(IFeature routeFeature, INetworkDataset networkDataset)
        {
            var segments = new List<PathSegment>();

            // 获取路径边信息

            //INetworkRoute route = routeFeature as INetworkRoute;
            //IEnumNetEID edgeEIDs = route.get_EdgeEIDs(true);

            //int edgeID;
            //while ((edgeID = edgeEIDs.Next()) != -1)
            //{
            //    INetworkEdge edge = networkDataset.GetEdge(edgeID);
            //    segments.Add(new PathSegment
            //    {
            //        EdgeID = edgeID,
            //        Length = edge.Length,
            //        Direction = edge.IsAlongDigitizedDirection ? "正向" : "逆向",
            //        StreetName = GetStreetName(edge)
            //    });
            //}
            return segments;
        }

        private static string GetStreetName(INetworkEdge edge)
        {
            // 实际应从网络属性获取道路名称
            IRow row = edge as IRow;
            return row?.get_Value(row.Fields.FindField("道路名称"))?.ToString() ?? "无名道路";
        }
        #endregion

        #region COM对象管理
        public void Dispose()
        {
            if (PathGeometry != null && Marshal.IsComObject(PathGeometry))
            {
                Marshal.ReleaseComObject(PathGeometry);
                PathGeometry = null;
            }
        }
        #endregion

        #region INotifyPropertyChanged
        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        protected bool SetField<T>(ref T field, T value, [CallerMemberName] string propertyName = null)
        {
            if (EqualityComparer<T>.Default.Equals(field, value)) return false;
            field = value;
            OnPropertyChanged(propertyName);
            return true;
        }
        #endregion
    }

    /// <summary>
    /// 路径分段详细信息
    /// </summary>
    public class PathSegment
    {
        public int EdgeID { get; set; }
        public double Length { get; set; }      // 米
        public double TimeCost { get; set; }     // 秒
        public string Direction { get; set; }
        public string StreetName { get; set; }
        public string Instruction { get; set; }  // 导航指令（如"左转进入XX路"）
    }
}